package com.jd.fruit.model.admin.shop;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jd.fruit.common.annotation.Table;
import com.jd.fruit.common.model.BaseModel;
import com.jd.fruit.common.util.StringUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

/**
 * 商品sku
 * 
 * @author lishunfeng
 * 
 */
@SuppressWarnings("serial")
@Table("t_category_attribute")
public class CategoryAttribute extends BaseModel<CategoryAttribute> {
	public static final CategoryAttribute dao = new CategoryAttribute();

	/**
	 * 保存商品SKU
	 * 
	 * @param role
	 */
	public void save(CategoryAttribute catattr) {
		try {
			catattr.set("id", StringUtil.getKey());
			catattr.save();
		} catch (Exception e) {
			throw new RuntimeException("分类属性Sku保存异常！", e);
		}
	}
	
	/**
	 * 保存分类对应属性值
	 * 
	 * @param role
	 */
	public void save(String attrs,String catId) {
		try {
			JSONObject jsonObjAttr=JSONObject.parseObject(attrs);
			JSONArray catAttrArray=jsonObjAttr.getJSONArray("attrs");
			CategoryAttribute catAttr=new CategoryAttribute();
		 	for (Object json : catAttrArray) {
		 		JSONObject rowJson = JSONObject.parseObject(String.valueOf(json));
		 		String attrid = rowJson.getString("attrid");
		 		String valueStr = rowJson.getString("values");
		 		String[] values=valueStr.split("#");
		 		for (int i = 0; i < values.length; i++) {
		 			catAttr.set("cat_id", catId);
		 			catAttr.set("attr_id", attrid);
		 			catAttr.set("attr_value", values[i]);
		 			this.dao.save(catAttr);
				}
			}
			
		} catch (Exception e) {
			throw new RuntimeException("分类属性Sku保存异常！", e);
		}
	}
	
	

	/**
	 * 删除分类所有关联的数据
	 * 
	 * @param roleid
	 */
	public void delAttrValuesRelationCat(String cat_id) {
		Db.deleteById("t_category_attribute", "cat_id", cat_id);
	}
	
	/**
	 * 根据分类ID查询出对应数据
	 * @param goodsId
	 * @return
	 */
	public List<CategoryAttribute> listByCat(String catId) {
		String sql = "SELECT * FROM `t_category_attribute` WHERE `cat_id`=?";
		return this.find(sql, catId);
	}
	
	/**
	 * 根据商品所属分类ID查询出关联属性数据
	 * @param goodsId
	 * @return
	 */
	public List<String> listByGoodsCateID(String catId) {
		String sql = "SELECT attr_value FROM `t_category_attribute` WHERE `cat_id`=?";
		return Db.query(sql, catId);
	}

	@Override
	public void initWhere() {
		// TODO Auto-generated method stub

	}
}
